from typing import Any, List
from fastapi import APIRouter, Depends
from fastapi.security import OAuth2PasswordBearer
from pydantic import BaseModel, Field

from api.login.login import GetUser_acl
from util.JWT import login_token, refresh_token_route, get_current_user

appLogin = APIRouter()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="login")  # 登录的url


class CommonResponseModel(BaseModel):
    code: int = Field(..., example=200)
    msg: str = Field(..., example="success")
    status: str
    data: Any


# Token的数据模型
class Token(BaseModel):
    access_token: str
    token_type: str
    refresh_token: str
    username: str
    routes: List[str]
    buttons: List[str]


class TokenResponse(CommonResponseModel):
    data: Token


# 用户登录的数据模型
class UserLogin(BaseModel):
    username: str
    password: str


# 用户登录
@appLogin.post("/", response_model=TokenResponse)
async def login(user_login: UserLogin):
    return login_token(user_login.username, user_login.password)


# 验证刷新token
@appLogin.post("/refresh_token")
async def refresh_token(id: dict = Depends(get_current_user)):
    print(id)
    return refresh_token_route(id)


# 获取用户权限
@appLogin.get("/user_acl", response_model=CommonResponseModel)
async def user_acl(id: dict = Depends(get_current_user)):
    df = GetUser_acl(id)
    return {
        "code": 200,
        "status": "ok",
        "msg": "success",
        "data": {
            "routes": df[df['acl_type'] == 0]['acl_name'].tolist(),
            "buttons": df[df['acl_type'] == 1]['acl_name'].tolist()
        }
    }



